<template>
    <div v-if="searchArr.length>0" style="position: relative">
        <div :class="{'search-hover':show}" class="search-head" @click.stop="dataHead">
            <span class="search-head-name"><my-icon type="icon-Vue3_search" style="margin-right: 0.5rem"></my-icon>{{
                    $ti18('rxList.searchForBtn', '搜索')
                }}</span>
        </div>
        <div v-if="show" class="search-list">
            <div class="search-list-hover">
                <div class="search-list-input" v-for="search in searchArr">
                    <div class="search-list-name">{{ search.fieldLabel }}:</div>
                    <div class="search-list-common">
                        <!--文本-->
                        <input v-if="search.fc=='textbox'" type="text"
                               v-model="query[search.autoFilter=='YES'?'Q_'+(search.tablePre?search.tablePre+'.':'')+search.fieldName+'_S_'+search.fieldOp:search.fieldName]"
                               :placeholder="search.emptytext"/>
                        <div v-else-if="search.fc=='datepicker'">
                            <!--日期-->
                            <div class="rx-date-select" @click="showPlugin(search.idx_)">
                                <span>{{
                                        query[search.autoFilter == 'YES' ? 'Q_' + (search.tablePre ? search.tablePre + '.' : '') + search.fieldName + '_D_' + search.fieldOp : search.fieldName] || $ti18('rxDecorator.select', "请选择")
                                    }}</span>
                                <i class="iconfont icon-icon-test41"></i>
                            </div>
                            <lingfeng-timepicker
                                :ref="search.idx_"
                                :type="search.format=='YYYY-MM-DD HH:mm:ss' ? 'datetime-all' :'date' "
                                :maxDate="maxDate"
                                @change="dateChange($event,search)"></lingfeng-timepicker>
                        </div>
                        <div v-else-if="search.fc=='rangepicker'">
                            <div class="rx-date-select" @click="showPlugin(search.idx_)">
                                <span>{{ getRangeDateStr(search) }}</span>
                                <i class="iconfont icon-icon-test41"></i>
                            </div>
                            <!--日期范围-->
                            <lingfeng-timepicker
                                :ref="search.idx_"
                                :type="search.format=='YYYY-MM-DD HH:mm:ss' ? 'datetime-all-range' :'date-range' "
                                :maxDate="maxDate"
                                @change="rangeDateChange($event,search)"></lingfeng-timepicker>
                        </div>
                        <div v-else-if="search.fc=='select'" style="margin-right: 1rem">
                            <!--下拉框-->
                            <next-data-select
                                :multiple="search.multiSelect"
                                v-model="query[search.autoFilter=='YES'?'Q_'+(search.tablePre?search.tablePre+'.':'')+search.fieldName+'_S_'+search.fieldOp:search.fieldName]"
                                :options="optionObj[search.idx_]"
                                :disabled="false"
                                :placeholder="i18n('dropSelect','下拉选择')"
                                optionsLabelKey="label"
                                optionsValueKey="value"
                            />
                        </div>
                        <div v-else-if="search.fc=='user'" style="margin-right: 1rem">
                            <RxVueUserDialog v-model="queryEcho[search.idx_]" @change="onChange($event,search)"
                                             :single="!search.multiSelect"></RxVueUserDialog>
                        </div>
                        <div v-else-if="search.fc=='group'" style="margin-right: 1rem">
                            <RxVueGroupDialog v-model="queryEcho[search.idx_]" @change="onChange($event,search)"
                                              :single="!search.multiSelect"></RxVueGroupDialog>
                        </div>
                        <div v-else-if="search.fc=='dialog'" style="margin-right: 1rem">
                            <rx-edit-button v-model:modelValue="queryEcho[search.idx_]" :ref="'dialog'+search.idx_"
                                            @btnClick="openDialog($event,search)"
                                            @deleteClose="deleteClose($event,search)"></rx-edit-button>
                        </div>
                    </div>
                </div>
            </div>
            <div class="tree-bottom">
                <div @click.stop="reset">{{ $ti18('rxList.resetBtn', '重置') }}</div>
                <div @click.stop="confirm">{{ $ti18('rxForm.okBtn', '确定') }}</div>
            </div>
        </div>
    </div>
</template>

<script>
import util from './util.js'
import dayjs from 'dayjs'
import {FormApi} from "@/api/FormApi.js";
import Dialog from "@/js/Dialog.js";
import RxVueGroupDialog from '@/components/RxVueGroupDialog.vue';
import RxVueUserDialog from '@/components/RxVueUserDialog';
import RxEditButton from '@/components/RxEditButton';

export default {
    name: "FormBoListSearch",
    props: {
        mobileSearch: {
            type: Array,
            default() {
                return [];
            }
        },
        queryParam: {
            type: Object,
            default() {
                return {}
            }
        }
    },
    components: {
        RxVueGroupDialog,
        RxVueUserDialog,
        RxEditButton,
    },
    mixins: [util],
    computed: {
        maxDate() {
            return {year: dayjs().year() + 10};
        }
    },
    data() {
        return {
            show: false,
            searchArr: [],//控件
            query: {},//查询数据
            //下拉框数据
            optionObj: {},
            queryEcho: {},//回显数据
        }
    },
    created() {
        this.init();
        this.initOptions();
    },
    methods: {
        i18n(name,text,key){
            return this.$ti18(name,text,"formSolutionLang",key);
        },
        init() {
            this.query = this.deepClone(this.queryParam);
            this.searchArr = this.mobileSearch.filter(item => {
                return item.type == 'query';
            });
            this.searchArr.forEach(res => {
                if (res.fc == ('user' || 'group') && res.defaultValConf) {
                    let list = JSON.parse(JSON.parse(res.defaultValConf).defaultVal);
                    let userList = []
                    list.forEach(res_ => {
                        userList.push({
                            name: res_.label,
                            id: res_.key
                        })
                    })
                    this.queryEcho[res.idx_] = userList;
                    this.userChange(userList, res)

                }
            })
        },
        deleteClose(item, paramMapping) {
            let self = this;
            let queryField = (paramMapping.tablePre ? paramMapping.tablePre + "." : "") + paramMapping.fieldName;
            let value = [];
            if (paramMapping.autoFilter == 'YES') {
                value = self.query["Q_" + queryField + "_S_" + paramMapping.fieldOp].split(",");
            } else {
                value = self.query[queryField + "_S_" + paramMapping.fieldOp].split(",");
            }
            value.filter((res, index) => {
                if (item.value == res) {
                    value.splice(index, 1)
                }
            })
            if (value.length > 0) {
                self.query["Q_" + queryField + "_S_" + paramMapping.fieldOp] = value.join(',')
            } else {
                self.query["Q_" + queryField + "_S_" + paramMapping.fieldOp] = ""
            }
        },
        openDialog(vm, paramMapping) {
            let dialog = paramMapping.dialog;
            let valueField = paramMapping.valueField;
            let textField = paramMapping.textField;
            let single = !paramMapping.multiSelect;
            if (!dialog) {
                this.$message.error(vm.$ti18('rxMsa.masWarn.configDialog', "请配置对话框"));
                return;
            }
            let self = this;
            let conf = {
                data: {
                    alias: dialog,
                    single: single
                },
                curVm: self,
            };
            Dialog.openDialog(conf, function (data) {
                if (data.action != 'ok') {
                    return;
                }
                let rows = data.data.rows;
                if (rows.length == 0) {
                    return;
                }
                let values = [];
                let btnValues = [];
                //多选
                if (!single) {
                    for (let i = 0; i < rows.length; i++) {
                        values.push(rows[i][valueField]);
                        btnValues.push(
                            {
                                "value": rows[i][valueField],
                                "label": rows[i][textField]
                            }
                        );
                    }
                } else {
                    values.push(rows[0][valueField]);
                    btnValues.push(
                        {
                            "value": rows[0][valueField],
                            "label": rows[0][textField]
                        }
                    );
                }
                self.$refs['dialog' + paramMapping.idx_][0].curVal = btnValues;
                let queryField = (paramMapping.tablePre ? paramMapping.tablePre + "." : "") + paramMapping.fieldName;
                if (paramMapping.autoFilter == 'YES') {
                    self.query["Q_" + queryField + "_S_" + paramMapping.fieldOp] = values.join(',');
                } else {
                    self.query[queryField + "_S_" + paramMapping.fieldOp] = values.join(',');
                }
                self.queryEcho[paramMapping.idx_] = btnValues
            });
        },
        //用户筛选
        userChange(val, search) {
            let idList = [];
            val.forEach(res_ => {
                idList.push(res_.id)
            })
            let queryField = (search.tablePre ? search.tablePre + "." : "") + search.fieldName;
            if (search.autoFilter == 'YES') {
                this.query["Q_" + queryField + "_S_" + search.fieldOp] = idList.join(',');
            } else {
                this.query[queryField + "_S_" + search.fieldOp] = idList.join(',');
            }
        },
        dataHead() {
            this.show = !this.show;
        },
        confirm() {
            this.show = false;
            let self = this;
            setTimeout(function () {
                self.$emit('search', self.query)
            }, 200)
        },
        reset() {
            this.show = false;
            this.query = {};
            this.queryEcho = {};
            let self = this;
            setTimeout(function () {
                self.$emit('search', self.query)
            }, 200)

        },
        onChange(value, search) {
            this.queryEcho[search.idx_] = value
            this.userChange(value, search)
        },
        showPlugin(key) {
            if (!this.$refs[key] || !this.$refs[key][0]) {
                return;
            }
            this.$refs[key][0].show();
        },
        getDate(paramMapping) {
            let defaultData = {
                startTime: paramMapping.fieldExt.value
            }
            return defaultData;
        },
        dateChange(value, search) {
            if (value instanceof Object && value.hasOwnProperty("show")) {
                return;
            }
            this.query[search.autoFilter == 'YES' ? 'Q_' + (search.tablePre ? search.tablePre + '.' : '') + search.fieldName + '_D_' + search.fieldOp : search.fieldName] = value
        },
        rangeDateChange(values, paramMapping) {
            if (values instanceof Object && values.hasOwnProperty("show")) {
                return;
            }
            let ary = [];
            ary.push(dayjs(values[0]).format(paramMapping.format || 'YYYY-MM-DD'));
            ary.push(dayjs(values[1]).format(paramMapping.format || 'YYYY-MM-DD'));
            let queryField = (paramMapping.tablePre ? paramMapping.tablePre + "." : "") + paramMapping.fieldName;
            if (paramMapping.autoFilter == 'YES') {
                this.query["Q_" + queryField + "_D_GE"] = ary[0];
                this.query["Q_" + queryField + "_D_LE"] = ary[1];
            } else {
                this.query[queryField + "_START"] = ary[0];
                this.query[queryField + "_END"] = ary[1];
            }
        },
        getRangeDateStr(paramMapping) {
            let value = '请选择';
            let queryField = (paramMapping.tablePre ? paramMapping.tablePre + "." : "") + paramMapping.fieldName;
            if (paramMapping.autoFilter == 'YES' && this.query["Q_" + queryField + "_D_GE"]) {
                return this.query["Q_" + queryField + "_D_GE"] + '-' + this.query["Q_" + queryField + "_D_LE"]
            } else if (this.query[queryField + "_START"]) {
                return this.query[queryField + "_START"] + '-' + this.query[queryField + "_END"]
            }
            return value;
        },
        getOptions(settings, key, params, type) {
            if (!settings) {
                return;
            }
            let options = [];
            //自定义
            if (settings == "self") {
                let dataSource = JSON.parse(params.props);
                for (let j = 0; j < dataSource.length; j++) {
                    options.push({
                        value: dataSource[j].key,
                        label: dataSource[j].name,
                    })
                }
                this.optionObj[key] = options;
            }
            //数据字典
            else if (settings == "dic") {
                FormApi.loadDicByPidAndDicId(params.dicKey, "").then(res => {
                    if (res.length && res.length > 0) {
                        for (let j = 0; j < res.length; j++) {
                            options.push({
                                id: res[j].pkId,
                                value: res[j].value,
                                label: res[j].name,
                                parentId: res[j].parentId,
                            })
                        }
                    }
                    if (type == 'tree') {
                        options = Util.listToTree(options, "id", "parentId");
                    }
                    this.optionObj[key] = options;
                });
            }
            //sql
            else if (settings == "sql") {
                if (!params.sql) {
                    return;
                }
                let textfield = params.sql_textfield;
                let valuefield = params.sql_valuefield;
                let parentfield = params.sql_parentfield;
                let sql = params.sql;
                FormApi.queryForJson(sql, {params: JSON.parse(params.params)}).then(res => {
                    let data = res.data;
                    if (data.length && data.length > 0) {
                        for (let j = 0; j < data.length; j++) {
                            options.push({
                                value: data[j][valuefield],
                                label: data[j][textfield],
                                parentId: data[j][parentfield],
                            })
                        }
                    }
                    if (type == 'tree') {
                        options = Util.listToTree(options, "value", "parentId");
                    }
                    this.optionObj[key] = options;
                });
            }
            //权限数据
            else if (settings == "grant") {
                if (params.grant) {
                    let grant = params.grant;
                    FormApi.loadByGrant(grant).then(res => {
                        for (let j = 0; j < res.data.length; j++) {
                            options.push({
                                value: res.data[j]["value"],
                                label: res.data[j]["label"],
                                parentId: res.data[j]["parentId"]
                            })
                        }
                        if (type == 'tree') {
                            options = Util.listToTree(options, "value", "parentId");
                        }
                        this.optionObj[key] = options;
                    })
                }
            }
        },
        initOptions() {
            //下拉框获取选项数据
            for (let i = 0; i < this.searchArr.length; i++) {
                let paramMapping = this.searchArr[i];
                if (paramMapping.fc && (paramMapping.fc == "select" || paramMapping.fc == "tree")) {
                    this.getOptions(paramMapping.from, paramMapping.idx_, paramMapping, paramMapping.type);
                }
            }
        },
    },
    watch: {
        query: {
            handler(val) {
                this.$emit('update:queryParam', val);
            },
            deep: true,
            immediate: true
        }
    }
}
</script>

<style scoped>
.search-list-common {
    padding-left: 1rem;
    margin-top: 0.5rem;
}

.search-list-hover {
    max-height: 15rem;
    overflow: auto;
}

.search-hover {
    color: #4794ff !important;
}

.search-head {
    display: flex;
    padding: 0.5rem 1rem;
    border-bottom: 1px solid #e8e8e8;
}

.search-head-name {
    flex: 1;
    text-align: left;
}

.search-list {
    background: white;
    z-index: 999;
    position: absolute;
    top: 2.3rem;
    right: 0rem;
    left: 0rem;
}

.search-list-input {
    display: flex;
    margin: .5rem 0rem;
    flex-direction: column;
}

.search-list-input input {
    height: 2rem;
    border: 1px solid #e8e8e8;
    flex: 1;
    border-radius: 5px;
    font-size: .8rem;
    margin-right: 1rem;
    padding-left: .5rem;
}

.search-list-name {
    margin-left: 1rem;
    min-width: 4rem;
    text-align: left;
}

.tree-bottom {
    display: flex;
    height: 2.5rem;
    line-height: 2.5rem;
    text-align: center;
    margin-top: 1rem;
}

.tree-bottom > div:nth-child(1) {
    flex: 1;
    color: #777777;
    border-top: 1px solid #e8e8e8;
}

.tree-bottom > div:nth-child(2) {
    color: #FFFFFF;
    flex: 1;
    background-color: #2871ff;
}

.rx-date-select i {
    line-height: 1.4rem;
    height: 1.4rem;
}

.rx-date-select {
    display: flex;
    border: none !important;
    align-items: center;
    margin-right: 1rem;
}

.rx-date-select span {
    margin-right: 0.2rem;
    line-height: 1.7rem;
    flex: 1;
}
</style>
